package cn.tedu.es.searcher;

import cn.tedu.es.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: LiuXingYu
 * @date: 2021/9/29 14:08
 */
@Component
public class StudentSearcher {

    // 用来执行 CriteriaQuery 的工具对象
    @Autowired
    private ElasticsearchOperations o;

    // 任意定义的搜索方法
    public List<Student> findByName(String nameKey) {
        Criteria c = new Criteria("name");
        c.is(nameKey);
        return exec(c);
    }

    public List<Student> findByBirthDate(String from, String to) {
        Criteria c = new Criteria("birthDate");
        c.between(from,to);
        return exec(c);
    }

    private List<Student> exec(Criteria c) {
        // 把条件, 封装到一个查询对象
        CriteriaQuery query = new CriteriaQuery(c);
        SearchHits<Student> searchHits = o.search(query, Student.class);

        /*List<Student> list = new ArrayList<>();
        for (SearchHit<Student> searchHit : searchHits) {
            Student s = searchHit.getContent();
            list.add(s);
        }*/
        // 方式二:  使用集合流 Stream AIP 和 lambda 表达式, 简化上面的代码
        List<Student> list = searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
        return list;
    }
}
